package com.china08.yxyapi.schedule.activity.healthcompetition;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.china08.yxyapi.entity.mg.huodong.healthcompetition.YxyCompetitionSchool;
import com.china08.yxyapi.entity.mg.huodong.healthcompetition.YxyCompetitionStudent;
import com.china08.yxyapi.repository.mg.huodong.YxyCompetitionSchoolRepository;
import com.china08.yxyapi.repository.mg.huodong.YxyCompetitionStudentRepository;
import com.china08.yxyapi.util.YxyScheduleRunnableUtil;

/**
 * 
 * 健康知识竞赛 学校管理员 活动统计 定时执行
 * 
 * @author shijiahe
 */
//
@Component
@Configurable
@EnableScheduling
public class HuodongHealthCompetitionSchStuScheduledTasks {

    private static Logger LOGGER = LoggerFactory.getLogger(HuodongHealthCompetitionSchStuScheduledTasks.class);
    @Value("${yx.rest.api.yx.path}")
    private String yxpath;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private YxyCompetitionStudentRepository yxyCompetitionStudentRepository;
    @Autowired
    private YxyCompetitionSchoolRepository yxyCompetitionSchoolRepository;

    // @Scheduled(cron = " 0 0/10 * * * * ")
    // @Scheduled(cron = " 0 0 2 * * * ")
    public void userRoleInitTask() {
        System.out.println("" //
                + "=================================================\n"
                + "-------------------------------------------------");

        // ##
        // 负载均衡环境:只在特定服务器上执行
        // ##
        // 检测定时任务是否可执行
        if (!YxyScheduleRunnableUtil.checkRunnable()) { return; }

        // 获取参与活动的学校
        List<YxyCompetitionSchool> list = yxyCompetitionSchoolRepository.findAll();
        for (YxyCompetitionSchool school : list) {
            try {
                HttpHeaders headers = new HttpHeaders();
                MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers.setContentType(type);
                headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
                Map<String, Object> formMap = new HashMap<String, Object>();
                formMap.put("schoolId", school.getSchoolId());
                HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(formMap, headers);
                ParRespModel httpResult = restTemplate.postForObject(yxpath + "/comm/stuinfolist/schandstage",
                        formEntity, ParRespModel.class);
                List<StudentInfo> students = httpResult.students;
                if (students != null && students.size() > 0) {
                    List<YxyCompetitionStudent> sendDataLst = new ArrayList<YxyCompetitionStudent>();
                    Integer index = 0;
                    for (StudentInfo studentInfo : students) {
                        index++;
                        // 查询参与作答学生是否存在,不存在添加,存在更新
                        YxyCompetitionStudent yxyCompetitionStudent = yxyCompetitionStudentRepository
                                .findTop1ByStudentId(studentInfo.studentId);
                        if (yxyCompetitionStudent == null) {
                            yxyCompetitionStudent = new YxyCompetitionStudent();
                            yxyCompetitionStudent
                                    .setStudentId(studentInfo.studentId == null ? "" : studentInfo.studentId);
                            yxyCompetitionStudent.setStatus(0);
                            yxyCompetitionStudent.setScore(0);
                            yxyCompetitionStudent.setPaperNum("");// 试卷编号根据学段判断
                            yxyCompetitionStudent.setImg("");
                            yxyCompetitionStudent.setStage("");
                            yxyCompetitionStudent.setAreaCodeProvince("");
                            yxyCompetitionStudent.setAreaNameProvince("");
                            yxyCompetitionStudent.setAreaCodeCity("");
                            yxyCompetitionStudent.setAreaNameCity("");
                            yxyCompetitionStudent.setAreaCodeDistrict("");
                            yxyCompetitionStudent.setAreaNameDistrict("");
                            yxyCompetitionStudent.setSchoolName("");
                        }
                        yxyCompetitionStudent.setSchoolId(school.getSchoolId());
                        yxyCompetitionStudent.setGrade(studentInfo.grade == null ? "" : studentInfo.grade);
                        yxyCompetitionStudent
                                .setStudentNick(studentInfo.studentname == null ? "" : studentInfo.studentname);
                        yxyCompetitionStudent.setClassId(studentInfo.classId == null ? "" : studentInfo.classId);
                        yxyCompetitionStudent.setClassName(studentInfo.classname == null ? "" : studentInfo.classname);
                        sendDataLst.add(yxyCompetitionStudent);
                        if (index == 300) {
                            yxyCompetitionStudentRepository.save(sendDataLst);
                            sendDataLst = new ArrayList<YxyCompetitionStudent>();
                            index = 0;
                        }
                    }
                    if (sendDataLst.size() > 0) {
                        yxyCompetitionStudentRepository.save(sendDataLst);
                    }
                }
                LOGGER.info("补全或更新学校" + school.getSchoolId() + "所有小学、初中、高中在读学生成功");
            } catch (Exception e) {
                LOGGER.info("获取学生列表接口链接失败");
                e.printStackTrace();
            }
        }
        LOGGER.info("健康知识竞赛学校管理员活动统计学生统计完成");

    }

    // 家长身份远程调用接口返回类型
    protected static class ParRespModel {
        public List<StudentInfo> students;
    }

    // 学生身份远程调用接口返回类型
    protected static class StudentInfo {
        // 学生id
        public String studentId;
        // 学生名称
        public String studentname;
        // 年级
        public String grade;
        // 班级id
        public String classId;
        // 班级名称
        public String classname;

    }
}
